package com.example.controller;

import com.example.bean.LoginLog;
import com.example.bean.UserBean;
import com.example.dao.LoginLogRepository;
import com.example.dao.UserDao;

import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

import java.text.SimpleDateFormat;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
public class LoginLogController {
//     @Autowired
//     private UserDaoImpl userDaoImpl;
    public String formatLoginDate(Date loginDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(loginDate);
    }
    @Autowired
    private LoginLogRepository loginLogRepository;
    private UserDao UserDao;

    @GetMapping("api/me/studyrecord/lastlogin")
    @ResponseBody
    public ResponseEntity<String> getLastLoginDate(@RequestParam String username) {
        List<LoginLog> loginLogs = loginLogRepository.findLoginLogsByUsername(username);
        if (loginLogs == null || loginLogs.isEmpty()) {
            return ResponseEntity.notFound().build(); // 用户没有登录记录
        }
        if (loginLogs.size() == 1)
        {
            return ResponseEntity.ok(formatLoginDate(loginLogs.get(0).getLoginDate()));
        }
        else
        {
            return ResponseEntity.ok(formatLoginDate(loginLogs.get(loginLogs.size()-2).getLoginDate()));
        }
    }


    @GetMapping("api/me/studyrecord/activedays")
    @ResponseBody
    public int countActiveDays(String username) {
        List<LoginLog> logs = loginLogRepository.findLoginLogsByUsername(username);

        // 将日期时间转换为日期字符串，忽略时分秒
        Set<String> uniqueDates = logs.stream()
                .map(log -> new SimpleDateFormat("yyyy-MM-dd").format(log.getLoginDate()))
                .collect(Collectors.toSet());
        // 活跃天数即为不同日期的数量
        System.out.println("active days count: "+uniqueDates.size());
        return uniqueDates.size();
    }

    @GetMapping("api/me/studyrecord/userlevel")
    @ResponseBody
    public int level(String username){
        System.out.println("Current user:"+ username);
        System.out.println("finding user level... : ");
        System.out.println("find user level: "+ UserDao.findByUserName(username));
        UserBean currentuser = UserDao.findByUserName(username).get(0);
        return currentuser.getLevel();
    }

    @GetMapping("api/me/studyrecord/userexp")
    @ResponseBody
    public int exp(String username){
        System.out.println("Current user:"+ username);
        System.out.println("finding user exp... : ");
        UserBean currentuser = UserDao.findByUserName(username).get(0);
        return currentuser.getExp();
    }
}